# -*- coding: utf-8 -*-
# @Time    : 2019/10/22 15:28
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : socket_http.py
# requests -> urlib -> socket
import socket
from urllib.parse import urlparse


def get_url(url):
    # 通过socket请求html
    url = urlparse(url)
    host = url.netloc
    path = url.path
    if path == "":
        path = "/"
    # 建立socket连接 进行http请求
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # client.setblocking(False)  # 立即返回 非阻塞式I/O， 缺陷
    client.connect((host, 80))  # 连接 阻塞不会消耗cpu

    # 如果采用非阻塞不停的询问连接是否建立好，需要while循环不同的去检查状态,只能去监听一个socket状态
    # 非阻塞式I/O使用情景不依赖之前的链接做计算任务或再次发起其它的连接接请求
    print("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host))
    # http协议发送的格式
    client.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode("utf8"))
    data = b""
    while True:
        d = client.recv(1024)
        if d:
            data += d
        else:
            break
    data = data.decode("utf8")
    html_data = data.split("\r\n\r\n")[1]
    print(data)
    print(html_data)
    client.close()


if __name__ == '__main__':
    # get_url("https://www.baidu.com")
    import time
    start_time = time.time()
    for url in range(20):
        url = f"http://jsonplaceholder.typicode.com/posts/{url}"
        get_url(url)
    print("finnal time", time.time() - start_time)
